<?php

namespace app\api\controller;

use think\Db;

//红包
class Redpacket extends BaseController
{
    //红包列表
    public function getList()
    {
        $user_info = session('user_info');
        $data = Db::name('red_packet')->where(['user_id' => $user_info['id'], 'not_open' => 1])->select();
        foreach ($data as $key => $value) {
            $order_info = Db::name('order')->find($value['order_id']);
            $product_info = Db::name('product')->field('id,name,pic')->find($order_info['product'][0]['product_id']);
            $user_info = Db::name('user')->field('id,name,avatar')->find($value['from_user_id']);
            $data[$key]['product'] = $product_info;
            $data[$key]['user'] = $user_info;
            $data[$key]['type'] = $value['type'];
            $data[$key]['not_settlemetn'] = intval($value['not_settlemetn']);
        }

        return success($data);
    }

    //拆红包
    public function open()
    {
        $id = input('post.id', '');
        if (!$id || 24 != strlen($id)) {
            return error('参数错误：错误的id');
        }
        $user_info = session('user_info');
        $user_db_info = Db::name('user')->find($user_info['id']);
        $data = Db::name('red_packet')->find($id);
        if (!$data || $data['user_id'] != $user_db_info['id']) {
            return error('未找到该红包');
        }
        if (1 != $data['not_open']) {
            return error('该红包已经拆开了');
        }
        if (1 == $data['not_settlemetn']) {
            return error('该红包还未结算,不能拆开');
        }
        Db::name('red_packet')->where(['id' => $id])->update(['not_open' => 0, 'open_time' => time()]);
        // 转到个人账户余额里（微信自动支付最小为1元 很多红包不满1元）
        $update_row = ['balance' => round($user_db_info['balance'] + $data['money'], 2)];
        if ('关注红包' != $data['type'] && '邀请红包' != $data['type']) {
            // 减少待结算金额
            $update_row['not_settlemetn'] = round($user_db_info['not_settlemetn'] - $data['money'], 2);
        }
        Db::name('user')->where('id', $user_db_info['id'])->update($update_row);
        // 写记录
        $uf_row = ['user_id' => $user_db_info['id'], 'money' => round($data['money'], 2), 'ct' => time(), 'type' => $data['type']];
        if ($data['order_id']) {
            $uf_row['order_id'] = $data['order_id'];
        }
        Db::name('user_finance')->insert($uf_row);

        cache('api_user_info_'.$user_db_info['id'], null);

        return success($data);
    }

    // 一键拆红包
    public function allOpen()
    {
        $ids = input('post.ids/a', '');
        if (!$ids || 0 == count($ids)) {
            return error('参数错误：错误的ids');
        }
        $user_info = session('user_info');
        $user_db_info = Db::name('user')->find($user_info['id']);
        $time = time();
        $total = 0;
        $new_ids = [];
        $uf = [];
        foreach ($ids as $id) {
            $red = Db::name('red_packet')->where(['id' => $id, 'user_id' => $user_db_info['id'], 'not_open' => 1, 'not_settlemetn' => ['neq', 1]])->find();
            if ($red) {
                $total += round($red['money'], 2);
                $new_ids[] = $id;
                $uf_row = ['user_id' => $user_db_info['id'], 'money' => round($red['money'], 2), 'ct' => $time, 'type' => $red['type']];
                if ($red['order_id']) {
                    $uf_row['order_id'] = $red['order_id'];
                }
                $uf[] = $uf_row;
            }
        }
        Db::name('red_packet')->where(['id' => ['in', $new_ids], 'user_id' => $user_db_info['id']])->update(['not_open' => 0, 'open_time' => $time]);
        //转到个人账户余额里（微信自动支付最小为1元 很多红包不满1元） 并写记录
        Db::name('user')->where('id', $user_db_info['id'])->update(['balance' => round($user_db_info['balance'] + $total, 2)]);
        Db::name('user_finance')->insertAll($uf);
        cache('api_user_info_'.$user_db_info['id'], null);

        return success(['total' => round($total, 2)]);
    }

    //红包记录
    public function record()
    {
        $user_info = session('user_info');
        // 感觉聚合要慢些 改select全部
        //    $r =  Db::name("red_packet")->aggregate(['_id' => null,'sum'=>['$sum'=>'$money']]);
        // $res = Db::name('red_packet')->where(['user_id' => $user_info['id']])->order(['_id'=>-1])->aggregate(['_id' => ['year' => ['$year' => '$ct'],'month' => ['$month' => '$ct'], 'day' => ['$dayOfMonth' => '$ct']], 'ids' => ['$push' => '$$ROOT']]);
        $result = [];
        $query['user_id'] = $user_info['id'];
        $query['not_open'] = 0;
        $limit = input('post.limit', 10);
        $page = input('post.page', 1);
        $order = ['ct' => -1];
        $data = Db::name('red_packet')->where($query)->order($order)->limit($limit)->page($page)->select();
        foreach ($data as $key => $value) {
            $row = [];
            $day = dayTime($value['ct']);
            $user_info = Db::name('user')->field('id,name,avatar')->find($value['from_user_id']);
            $row['type'] = $value['type'];
            $row['user'] = $user_info;
            $row['money'] = round($value['money'], 2);
            $result[$day][] = $row;
        }

        return success($result);
    }
}
